package com.chiao.service.admin;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chiao.core.ExtNode;
import com.chiao.dao.admin.DeptDao;
import com.chiao.entity.admin.Dept;
import com.chiao.entity.admin.ExtGrid;

@Service
public class DeptService {

	@Autowired
	DeptDao deptDao;

	public String listDepts() {
		List<Map<String, Object>> deptList = deptDao.listDepts();
		HashMap nodeList = new HashMap();
		ExtNode root = null;
		for (Map<String, Object> map : deptList) {
			ExtNode node = new ExtNode();
			node.setId((Integer) map.get("deptid"));
			node.setText((String) map.get("deptname"));
			node.setParentId((Integer) map.get("pid"));
			node.setSortNo((Integer) map.get("sortno"));
			nodeList.put(node.getId(), node);
		}
		Set entrySet = nodeList.entrySet();
		for (Iterator it = entrySet.iterator(); it.hasNext();) {
			ExtNode node = (ExtNode) ((Map.Entry) it.next()).getValue();
			if (node.getParentId() == 0) {
				root = node;
			} else {
				((ExtNode) nodeList.get(node.getParentId())).getChildren().add(node);
			}
		}
		if(root==null){
			return "[]";
		}else{
			return "[" + root.toString() + "]";
		}
	}
	
	public int addDept(Dept d){
		return deptDao.addDept(d);
	}
	
	public ExtGrid<Dept> listDeptsById(int id){
		ExtGrid<Dept> eg=new ExtGrid<Dept>();
		eg.setSuccess(true);
		List<Dept> list=deptDao.listDeptsById(id);
		eg.setItems(list);
		return eg;
	}

	public int deleteDeptByIds(String ids) {
		return deptDao.deleteDeptByIds(ids);
		
	}

	public int updateDept(Dept dept) {
		return deptDao.updateDept(dept);
	}
}
